<template>
  <div class="index">
    <div class="logo">
      <div class="logo_img">
        <img src="../assets/img/newsLogo.jpg" alt="加载失败">
      </div>
      <div class="title">cdy新闻网</div>
      <router-link to="/administration">
        <el-button type="info" size="mini" class="admin" v-if="adminToken">管理员入口</el-button>
      </router-link>
    </div>
    <div class="user">
      <span class="el-icon-user"></span>
      <span class="login">
        <span v-if="!user_name">
          <router-link to="/login">登录</router-link>
        </span>
        <span v-else class="userName">
          {{user_name}}
          <el-button
                  size="mini"
                  class="logout"
                  @click="logout">退出</el-button>
        </span>
      </span>
    </div>
  </div>
</template>

<script>
  import {mapState} from "vuex";

  export default {
    name: "Header",
    data() {
      return {
        user_name: '',
        adminToken: ''
      }
    },
    computed: {
      ...mapState(['user_info'])
    },
    methods: {
      logout() {
        window.sessionStorage.clear()
        this.$store.state.user_info = {}
        location.reload()
      }
    },
    created() {
      if (window.sessionStorage.getItem('token')) {
        this.user_name = JSON.parse(window.sessionStorage.getItem('userInfo')).username
      }
      if (window.sessionStorage.getItem('adminToken')) {
        this.adminToken = window.sessionStorage.getItem('adminToken')
      }
    }
  }
</script>

<style scoped lang="less">
  .admin {
    margin-left: 10px;
  }

  .index {
    width: 100%;
    background: #333333;
    overflow: hidden;
    padding: 10px 50px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .logo {
      height: 40px;
      display: flex;
      justify-content: center;
      align-items: center;

      .title {
        color: white;
        font-size: 20px;
        margin-left: 20px;
      }

      .logo_img {
        width: 40px;
      }

      img {
        width: 100%;
        height: 100%;
      }
    }

    .user {
      color: white;
      font-size: 20px;
      cursor: pointer;

      .login {

        span {
          color: white;
        }

        .userName {
          display: inline-block;

          .logout {
            background: none;
            color: white;
            font-size: 14px;
            margin-left: 5px;
          }
        }

        a {
          color: white;
        }
      }
    }
  }
</style>